import React, { useState } from 'react';
import { Card, Spin, Button, Form, message, DatePicker, Select } from 'antd';
import { useMount } from 'react-use';
import moment from 'moment';

import { BottomAction } from '@/components';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { isSuccess } from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';
import { getBaseKpi, updateBaseKpi, getKpiSalaryItems } from '@/services/salaryManage/salaryCalculate';
import LimitInput from '@/components/LimitInput';

import { NumberInput } from '@/pages/SalaryManage/components/NumberInput';
import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';

const { Item } = Form;
const { MonthPicker } = DatePicker;

const numberOption = name => ({
    validateFirst: true,
    rules: [
        {
            required: true,
            message: `请填写【${name}】`
        },
        {
            type: 'number',
            min: 0,
            message: `【${name}】不能小于0`
        },
        {
            type: 'number',
            max: 9999999999.99,
            message: `【${name}】不能超过10亿`
        },
        {
            type: 'number',
            message: `【${name}】输入长度不能大于12`
        },
        {
            validator: (rule, value, callback) => {
                const dotPosition = String(value).indexOf('.');
                // 小数位数超过8位时
                if (
                    dotPosition > 0 &&
                    String(value).length > dotPosition + 1 &&
                    String(value).substr(dotPosition + 1).length > 8
                ) {
                    callback(new Error());
                } else {
                    callback();
                }
            },
            message: '小数位数不能超过8位'
        }
    ]
});

const wrapperPageModel = pageModel => {
    const { year, month, kpiStartYear, kpiStartMonth, kpiEndYear, kpiEndMonth, ...rel } = pageModel;
    // 所属月份
    if (year && month) {
        rel.v_period = moment(`${year}-${(month < 10 ? '0' : '') + month}`);
    }

    // 开始区间
    if (kpiStartYear && kpiStartMonth) {
        rel.v_kpiStart = moment(`${kpiStartYear}-${(kpiStartMonth < 10 ? '0' : '') + kpiStartMonth}`);
    }

    // 结束区间
    if (kpiEndYear && kpiEndMonth) {
        rel.v_kpiEnd = moment(`${kpiEndYear}-${(kpiEndMonth < 10 ? '0' : '') + kpiEndMonth}`);
    }

    return rel;
};

const getPostData = (pageModel, formValue) => {
    const { v_period, v_kpiStart, v_kpiEnd, ...otherFormValue } = formValue;
    const rel = { ...pageModel, ...otherFormValue };

    if (v_period) {
        rel.year = v_period.year();
        rel.month = v_period.month() + 1;
    } else {
        rel.year = null;
        rel.month = null;
    }

    if (v_kpiStart) {
        rel.kpiStartYear = v_kpiStart.year();
        rel.kpiStartMonth = v_kpiStart.month() + 1;
    } else {
        rel.kpiStartYear = null;
        rel.kpiStartMonth = null;
    }

    if (v_kpiEnd) {
        rel.kpiEndYear = v_kpiEnd.year();
        rel.kpiEndMonth = v_kpiEnd.month() + 1;
    } else {
        rel.kpiEndYear = null;
        rel.kpiEndMonth = null;
    }

    return rel;
};

const SalaryPayrollTaxEdit = ({ form, location }) => {
    const [loading, setLoading] = useState(false);
    const [pageModel, setPageModel] = useState({});
    const [kpiSalaryItems, setKpiSalaryItems] = useState([]);
    const { getFieldDecorator } = form;

    const { id } = location.query;

    // 取消
    const onCancel = () => pageTabUtil.closeTab();

    // 保存
    const onSave = () => {
        form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                return;
            }

            const postData = getPostData(pageModel, values);

            if (
                postData.kpiEndYear * 100 + postData.kpiEndMonth <
                postData.kpiStartYear * 100 + postData.kpiStartMonth
            ) {
                message.error('【结束区间】必须大于等于【开始区间】');
                return;
            }

            setLoading(true);
            updateBaseKpi(postData)
                .then(response => {
                    setLoading(false);
                    if (!isSuccess(response)) {
                        message.error(response.msg);
                        return;
                    }
                    message.success('保存成功！');
                    tabMessageUtil.noticeFromRefresh();
                    pageTabUtil.closeTab();
                })
                .catch(() => {
                    setLoading(false);
                });
        });
    };

    useMount(async () => {
        setLoading(true);
        try {
            const pageModelResponse = await getBaseKpi({ id });
            setLoading(false);
            if (isSuccess(pageModelResponse)) {
                const responseModel = wrapperPageModel(pageModelResponse.data);
                setPageModel(responseModel);

                const salaryItemsResponse = await getKpiSalaryItems(responseModel.organizationCode);
                if (isSuccess(salaryItemsResponse)) {
                    setKpiSalaryItems(salaryItemsResponse.data);
                } else {
                    message.error(pageModelResponse.msg);
                }
            } else {
                message.error(pageModelResponse.msg);
            }
        } catch (e) {
            setLoading(false);
        }
    });

    return (
        <PageHeaderWrapper type="success">
            <Card bordered={false} title="编辑绩效系数">
                <Spin spinning={loading}>
                    <Form
                        layout="horizontal"
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}
                        style={{ maxWidth: '630px' }}
                    >
                        <Item label="行政机构">
                            <OrganizationNameConnect organizationCode={pageModel?.organizationCode} />
                        </Item>
                        <Item label="员工姓名">
                            <span style={{ whiteSpace: 'nowrap' }}>
                                {pageModel?.employeeNo} {pageModel?.name}
                            </span>
                        </Item>
                        <Item label="所属月份">
                            {getFieldDecorator('v_period', {
                                initialValue: pageModel?.v_period,
                                rules: [{ required: true, message: '请选择所属月份' }]
                            })(<MonthPicker />)}
                        </Item>
                        <Item label="绩效薪资类型">
                            {getFieldDecorator('salaryItemId', {
                                initialValue: pageModel?.salaryItemId,
                                rules: [{ type: 'string', required: true, message: '请选择【绩效薪资类型】！' }]
                            })(
                                <Select style={{ width: 200 }}>
                                    {kpiSalaryItems.map(item => (
                                        <Select.Option key={item.id} value={item.id}>
                                            {item.itemName}
                                        </Select.Option>
                                    ))}
                                </Select>
                            )}
                        </Item>
                        <Item label="开始区间">
                            {getFieldDecorator('v_kpiStart', {
                                initialValue: pageModel?.v_kpiStart,
                                rules: [{ required: true, message: '请选择【开始区间】！' }]
                            })(<MonthPicker />)}
                        </Item>
                        <Item label="结束区间">
                            {getFieldDecorator('v_kpiEnd', {
                                initialValue: pageModel?.v_kpiEnd,
                                rules: [{ required: true, message: '请选择【结束区间】！' }]
                            })(<MonthPicker />)}
                        </Item>
                        <Item label="绩效系数">
                            <div style={{ width: '145px' }}>
                                {getFieldDecorator('kpiNum', {
                                    initialValue: pageModel?.kpiNum,
                                    ...numberOption('绩效系数')
                                })(<NumberInput thousandsSeparator="," maxLength={15} />)}
                            </div>
                        </Item>
                        <Item label="补充说明">
                            {getFieldDecorator('remark', {
                                initialValue: pageModel?.remark
                            })(<LimitInput maxLength={500} area showNumber rows={3} placeholder="补充说明..." />)}
                        </Item>
                    </Form>
                    <BottomAction>
                        <Button onClick={onCancel}>取消</Button>
                        <Button type="primary" onClick={onSave}>
                            确定
                        </Button>
                    </BottomAction>
                </Spin>
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(Form.create()(SalaryPayrollTaxEdit));
